package com.qqt.csr.route.entity;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Lists;
import com.qqt.csr.route.assembler.RouteTaskAssembler;
import com.qqt.csr.route.dto.req.CreatingRouteTaskDTO;
import com.qqt.csr.route.dto.resp.SkillSetDTO;
import com.qqt.csr.route.enums.RouteTaskEventEnum;
import com.qqt.csr.route.enums.RouteTaskStatusEnum;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.mapping.FieldType;

import java.io.Serial;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@Document(collection = "csr_route_task")
// @CompoundIndexes({
//         @CompoundIndex(name = "idx_TCCID", def = "{'tenantId': 1, 'channelId': 1, 'channelUserId': 1}")
// })
public class RouteTask implements Serializable {
    @Serial
    private static final long serialVersionUID = -4721182994747787001L;

    /**
     * 任务id
     */
    @Id
    private String id;

    /**
     * 租户id
     */
    private String tenantId;

    /**
     * 渠道id
     */
    private String channelId;

    /**
     * 渠道用户id
     */
    private String channelUserId;

    /**
     * im账户id
     */
    @Indexed(name = "idx_accountId")
    private String accountId;

    /**
     * 会话id
     */
    @Indexed(name = "idx_conId")
    private String conversationId;

    /**
     * 路由任务状态
     */
    private RouteTaskStatusEnum status;

    /**
     * 路由规则
     */
    private RouteDistributionRule routeRule;

    /**
     * 已确认的业务规则
     */
    private RouteBizRule routeBizRule;

    /**
     * 技能组配置
     */
    private SkillSetDTO skillSet;

    /**
     * 计划选择的技能组id，不包含已确认的技能组id
     */
    private List<Long> planSkillSetIdList;

    /**
     * 接待客服id
     */
    @Field(targetType = FieldType.STRING)
    private Long csId;

    /**
     * 访客业务已选择错误次数
     */
    private Integer bizSelectErrorCount;

    /**
     * 任务状态事件列表
     */
    private List<RouteTaskEvent> eventList;

    /**
     * 创建时间
     */
    @Field(targetType = FieldType.STRING)
    private Date createTime;

    /**
     * 最近一次出队时间
     */
    @Field(targetType = FieldType.STRING)
    private Date outQueueTime;

    /**
     * 已出队次数
     */
    private Integer outQueueCount;

    /**
     * 入队时间
     */
    @Field(targetType = FieldType.STRING)
    private Date inQueueTime;

    /**
     * 添加事件
     *
     * @param eventEnum
     */
    @JsonIgnore
    public void addEvent(RouteTaskEventEnum eventEnum) {
        if (eventList == null) {
            eventList = Lists.newArrayList();
        }
        Date currentDate = new Date();
        DateUtil.offsetSecond(currentDate, 1);
        eventList.add(RouteTaskEvent.builder().name(eventEnum).createTime(DateUtil.formatDateTime(currentDate)).build());
        status = eventEnum.getTo();
    }

    /**
     * 增加访客业务选择错误次数
     */
    @JsonIgnore
    public void increaseBizSelectErrorCount(){
        if(bizSelectErrorCount == null){
            bizSelectErrorCount = 0;
        }
        bizSelectErrorCount++;
    }

    @JsonIgnore
    public void bindSkillSet(SkillSetDTO skillSetDTO){
        skillSet = skillSetDTO;
        if(CollectionUtils.isNotEmpty(planSkillSetIdList)){
            planSkillSetIdList.remove(skillSetDTO.getSkillSetId());
        }
    }

    /**
     * 累计出队次数
     */
    @JsonIgnore
    public void increaseOutQueueCount(){
        if(outQueueCount == null){
            outQueueCount = 0;
        }
        outQueueCount++;
    }

    /**
     * 创建任务
     *
     * @param routeTaskDTO
     * @param routeRule
     * @return
     */
    public static RouteTask create(CreatingRouteTaskDTO routeTaskDTO, RouteDistributionRule routeRule) {
        RouteTask routeTask = RouteTaskAssembler.INSTANCE.toRouteTask(routeTaskDTO);
        routeTask.setRouteRule(routeRule);
        routeTask.addEvent(RouteTaskEventEnum.CREATED);
        routeTask.setCreateTime(new Date());
        return routeTask;
    }
}
